package dal

import (
	"github.com/gin-gonic/gin"
	"honghu_be/dal/po"
)

func CreateBox(c *gin.Context, boxPo *po.Box) error {
	sql := GetDB().Model(po.Box{})
	return sql.Create(boxPo).Error
}

func UpdateBox(c *gin.Context, boxId int, boxPo *po.Box) error {
	sql := GetDB().Model(po.Box{})
	sql = sql.Where("id = ?", boxId)
	err := sql.Updates(boxPo).Error
	if err != nil {
		return err
	}
	sql.First(boxPo)
	return err
}

func DeleteBox(c *gin.Context, boxId int) error {
	sql := GetDB().Model(po.Box{})
	return sql.Delete(po.Box{}, boxId).Error
}

type GetBoxesRequest struct {
	BoxId  int
	Limit  int
	Offset int
}

func GetBoxes(c *gin.Context, req *GetBoxesRequest) ([]*po.Box, error) {
	var pos []*po.Box
	sql := GetDB().Model(po.Box{})
	if req.BoxId != 0 {
		sql = sql.Where("id = ?", req.BoxId)
	}
	if req.Limit > 0 {
		sql = sql.Limit(req.Limit)
	} else {
		sql = sql.Limit(1)
	}
	if req.Offset > 0 {
		sql = sql.Offset(req.Offset)
	}
	sql = sql.Find(&pos)
	return pos, sql.Error
}
